# from requests import Response
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializers.orders import OrderSerializer, OrdersSerializer
from meiduo_admin.utils import PageNum
from orders.models import OrderInfo


class OrdersView(ModelViewSet):

    serializer_class = OrdersSerializer
    queryset = OrderInfo.objects.all()
    pagination_class = PageNum

    # 在视图中定义status方法修改订单状态
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        # 获取订单对象
        order = self.get_object()
        # 获取要修改的状态值
        status = request.data.get('status')
        # 修改订单状态
        order.status = status
        order.save()
        # 返回结果
        ser = self.get_serializer(order)
        return Response({
            'order_id':order.order_id,
            'status':status
        })

    def get_queryset(self):
        # 提取keyword
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id=keyword)


class Order_pkView(APIView):
    def get(self, request, pk):
        orders = OrderInfo.objects.get(order_id = pk)
        serializer = OrderSerializer(instance=orders)
        return Response(serializer.data)
